package gxprod.androidai;

import gxprod.androidai.fetch.FetchWeather.WeatherModel;

import java.util.Hashtable;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.telephony.TelephonyManager;

/**
 * Holds information about the user. Needs a save and load function,
 * but not everything should go into the same file.
 * @author Josh Maleszewski
 */
public class DataCollection {

	public static final String USER_NAME 					= "name";
	public static final String USER_NICNAME 				= "nicname";
	public static final String USER_AGE 					= "age";
	public static final String USER_MEASUREMENT_SYSTEM 		= "measureSystem";
	public static final String USER_HOME_TOWN 				= "homeTown";

	public static final String AI_TOLD_USER_MY_NAME			= "toldName";
	public static final String AI_HAS_RUN_BEFORE 			= "runBefore";
	public static final String AI_ZIPCODE					= "zipCode";

	
	public static final int MEASUREMENT_SYSTEM_METRIC = 1;
	public static final int MEASUREMENT_SYSTEM_IMPERIAL = 2;

	public static Hashtable<String, Object> User;
	public static Hashtable<String, Object> AI;
	public static Hashtable<String, Object> Aliases;
	public static Hashtable<String, Object> Memory;

	private static boolean isLoaded = false;	
	private static Context backRef;

	public static void loadFromFile(Context context) {		

		backRef = context;

		if(isLoaded) return;
		isLoaded = true;

		SharedPreferences prefs;

		if(User == null) User = new Hashtable<String, Object>();
		if(AI == null) AI = new Hashtable<String, Object>();
		if(Aliases == null) Aliases = new Hashtable<String, Object>();

		prefs = context.getSharedPreferences("androidai.user", Context.MODE_WORLD_READABLE);
		User.putAll(prefs.getAll());		

		prefs = context.getSharedPreferences("androidai.ai", Context.MODE_WORLD_READABLE);
		AI.putAll(prefs.getAll());		

		prefs = context.getSharedPreferences("androidai.aliases", Context.MODE_WORLD_READABLE);
		Aliases.putAll(prefs.getAll());

		prefs = context.getSharedPreferences("androidai.memory", Context.MODE_PRIVATE);
		Aliases.putAll(prefs.getAll());
	}

	public static void saveToFile(Context context) {
		SharedPreferences prefs = context.getSharedPreferences("androidai.user", Context.MODE_WORLD_READABLE);
		Editor edit = prefs.edit();
		edit.clear();

		Object[] keys = User.keySet().toArray();  
		for(int i = 0; i < keys.length; i++) 
			edit.putString(keys[i].toString(), User.get(keys[i]).toString());
		edit.apply();

		prefs = context.getSharedPreferences("androidai.ai", Context.MODE_WORLD_READABLE);
		edit = prefs.edit();
		keys = AI.keySet().toArray();  
		for(int i = 0; i < keys.length; i++) 
			edit.putString(keys[i].toString(), User.get(keys[i]).toString());
		edit.apply();

		prefs = context.getSharedPreferences("androidai.aliases", Context.MODE_WORLD_READABLE);
		edit = prefs.edit();
		keys = Aliases.keySet().toArray();  
		for(int i = 0; i < keys.length; i++) 
			edit.putString(keys[i].toString(), Aliases.get(keys[i]).toString());
		edit.apply();

		prefs = context.getSharedPreferences("androidai.memory", Context.MODE_PRIVATE);
		edit = prefs.edit();
		keys = Aliases.keySet().toArray();  
		for(int i = 0; i < keys.length; i++) 
			edit.putString(keys[i].toString(), Aliases.get(keys[i]).toString());
		edit.apply();
	}


	public static String getZipCode(Context context) {
		String zip = (String) AI.get(AI_ZIPCODE);
		if(zip == null) {
			AIActivity.get().adapter.outputTemp("Getting Location");
			
		}
		return zip;
	}

	public static String updateZip(Context context) {
		LocationManager provider = (LocationManager) context.getSystemService("location");
		Location loc = provider.getLastKnownLocation("location");

		try {
			XPath xpath = XPathFactory.newInstance().newXPath();
			String expression = "//GeocodeResponse/result/address_component[type=\"postal_code\"]/long_name/text()";
			InputSource inputSource = new InputSource("https://maps.googleapis.com/maps/api/geocode/xml?latlng=" + loc.getLatitude() + "," + loc.getLongitude() + "&sensor=true");
			String zip = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
			if(zip != null)
				AI.put(AI_ZIPCODE, zip);
			return zip;
		} catch (XPathExpressionException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isOnline(Context context) {
		ConnectivityManager cm =
				(ConnectivityManager) backRef.getSystemService(Context.CONNECTIVITY_SERVICE);
		return cm.getActiveNetworkInfo().isConnectedOrConnecting();
	}


	public static boolean usesMetricSystem() {
		Object o = DataCollection.User.get(DataCollection.USER_MEASUREMENT_SYSTEM);
		if(o != null)
			return ((Integer)o) == DataCollection.MEASUREMENT_SYSTEM_METRIC;
		return false;
	}

	public static void firstLaunch(Context context) {
		TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

		if(tm.getSimCountryIso().equalsIgnoreCase("us"))	
			User.put(USER_MEASUREMENT_SYSTEM, MEASUREMENT_SYSTEM_IMPERIAL);
		else
			User.put(USER_MEASUREMENT_SYSTEM, MEASUREMENT_SYSTEM_METRIC);
	}

	private static WeatherModel weather;
	public static WeatherModel getWeather() { return weather; }
	public static void setWeather(WeatherModel wm) { weather = wm; }

}

